import { BaseResponse } from '@/common/BaseResponse';
import { Dynamic } from '@/entity/dynamic.entity';
import { User } from '@/entity/user.entity';
import { RECORD_STATUS } from '@/enum/common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PageParamDto } from './dto/page-param.dto';

@Injectable()
export class DynamicService {
  constructor(
    @InjectRepository(Dynamic)
    private readonly dynamicRepository: Repository<Dynamic>,
  ) {}

  async dynamicListSelect(pageParamDto: PageParamDto) {
    const qb = this.dynamicRepository.createQueryBuilder('dynamic');
    let result = qb;
    console.log('pageParamDto', PageParamDto);

    if (pageParamDto.type) {
      result = qb.andWhere('dynamic.type = :type', {
        type: pageParamDto.type,
      });
    }

    if (pageParamDto.content) {
      result = qb.andWhere(`dynamic.content like '%${pageParamDto.content}%'`);
    }
    result
      .andWhere('dynamic.status = :status', {
        status: RECORD_STATUS.SHOW,
      })
      .leftJoinAndMapOne(
        'dynamic.userInfo',
        User,
        'user',
        'user.id = dynamic.user_id',
      )
      .limit(pageParamDto.size)
      .offset((pageParamDto.page - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();

    return BaseResponse.toSuccesJustData({
      page: Number(pageParamDto.page),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }

  async deleteDynamic(id: number) {
    const result = await this.dynamicRepository.findOne({
      where: {
        id,
      },
    });
    result.status = RECORD_STATUS.DISABLE;
    return this.dynamicRepository.update(result.id, result);
  }
}
